package top.ffhome.multithread.ch04.demo02;

import java.util.concurrent.TimeoutException;

public class Host {
    //超时时间
    private final long timeout;
    //方法正常执行时值为true
    private boolean ready = false;

    public Host(long timeout) {
        this.timeout = timeout;
    }

    //修改状态
    public synchronized void setExecutable(boolean on) {
        ready = on;
        notifyAll();
    }

    //检查状态之后再执行
    public synchronized void execute() throws TimeoutException, InterruptedException {
        //开始时间
        long start = System.currentTimeMillis();
        while (!ready) {
            //当前时间
            long now = System.currentTimeMillis();
            //剩余的等待时间
            long rest = timeout - (now - start);
            if (rest <= 0) {
                throw new TimeoutException("now - start = " + (now - start) + ", timeout = " + timeout);
            }
            wait(rest);
        }
        doExecute();
    }

    //实际的处理
    private void doExecute() {
        System.out.println(Thread.currentThread().getName() + " calls doExecute");
    }
}
